package deyi.dao;

import deyi.entity.DeviceEntity;
import deyi.entity.DeviceconfigEntity;
import deyi.entity.DevicedataEntity;
import deyi.log.AppLogger;
import deyi.nbtype.DeviceConfigInfo;
import deyi.utils.HibernateUtil;
import deyi.utils.SpringContextUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.sql.Timestamp;
import java.util.List;

@Service
@Transactional
public class DeviceDataDBImpl implements DeviceDataDB{


    @Override
    public void batchInsert(List<DevicedataEntity> listDeviceData,List<DeviceConfigInfo> listDeviceConfigInfo) {
        Session session= null;
        Transaction tx = null;

        HibernateUtil hibernateUtil = (HibernateUtil) SpringContextUtil.getBean("hibernateutil");
        session = hibernateUtil.getSessionFactory().openSession();
        if(!session.getTransaction().isActive()){
            tx = session.beginTransaction();
        }else {
            tx=session.getTransaction();
        }
        try {
            //保存设备上报数据
            if(listDeviceData.size() > 0){
                for(DevicedataEntity dData : listDeviceData){
                    session.save(dData);
                }
            }
            //更新配置表配置
            if(listDeviceConfigInfo.size() > 0){
                for(DeviceConfigInfo configInfo : listDeviceConfigInfo){
                    DeviceconfigEntity originalConfigObj = session.get(DeviceconfigEntity.class,configInfo.getConfigId());
                    originalConfigObj.setConfigresult(configInfo.getDeviceStatus());
                    originalConfigObj.setConfigresultdate(new Timestamp(configInfo.getRevConfigTime().getTime()));
                    session.update(originalConfigObj);
                }
            }
            //更新设备信息表
            if(listDeviceConfigInfo.size() > 0){
                for(DeviceConfigInfo configInfo : listDeviceConfigInfo){
                    DeviceEntity device = session.get(DeviceEntity.class,configInfo.getDeviceSn());
                    device.setDevicestatus(configInfo.getDeviceStatus());
                    session.update(device);
                }
            }
        }catch (HibernateException ex){
            tx.rollback();
            AppLogger.logError(ex);
            ex.printStackTrace();
        }finally {
            session.flush();
            session.clear();
            tx.commit();
            session.close();
        }
    }
}
